<!-- 消息列表组件 -->
<template>
	<div class="messages-container" ref="messagesContainer" @scroll="handleScroll">
		<!-- 加载更多按钮 -->
		<div v-if="hasMoreHistory" class="load-more-container">
			<a-button @click="loadMoreHistory" :loading="loadingHistory" size="small" type="dashed">
				<template #icon>
					<UpOutlined />
				</template>
				加载更多历史消息
			</a-button>
		</div>

		<!-- 消息列表 -->
		<MessageItem
			v-for="(message, index) in messages"
			:key="message.id || `msg-${index}-${message.timestamp?.getTime() || Date.now()}-${message._updateKey || ''}`"
			:message="message"
			:user-avatar="userAvatar"
			:user-name="userName"
		/>

		<!-- 工具调用加载指示器 -->
		<ToolLoadingIndicator
			:generating="generating"
			:last-tool-message="lastToolMessage"
			:is-tool-calling="isToolCalling"
		/>

		<!-- 正在生成指示器 -->
		<div v-if="generating && !isToolCalling" class="generating-indicator">
			<a-spin size="small" />
			<span>正在疯狂加班码字中 ...</span>
		</div>

		<!-- 滚动到底部按钮 -->
		<div v-if="!autoScrollEnabled && messages.length > 0" class="scroll-to-bottom">
			<a-button type="primary" shape="circle" size="small" @click="scrollToBottomManually" class="scroll-btn">
				<template #icon>
					<DownOutlined />
				</template>
			</a-button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue'
import { MessageItem, ToolLoadingIndicator } from './message'
import { detectToolMessage } from '@/utils/markdownRenderer'

interface Message {
	id?: number
	role: 'user' | 'assistant'
	content: string
	timestamp: Date
	isHistoryMessage?: boolean
	_updateKey?: number // 添加更新键用于强制重新渲染
}

interface Props {
	messages: Message[]
	generating: boolean
	hasMoreHistory: boolean
	loadingHistory: boolean
	autoScrollEnabled: boolean
	userAvatar?: string
	userName?: string
}

interface Emits {
	(e: 'loadMoreHistory'): void
	(e: 'scroll', event: Event): void
	(e: 'scrollToBottom'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const messagesContainer = ref<HTMLElement>()

// 检测最后一条消息是否是工具调用
const lastToolMessage = computed(() => {
	const lastMessage = props.messages[props.messages.length - 1]
	return lastMessage?.content || ''
})

// 是否正在进行工具调用
const isToolCalling = computed(() => {
	if (!props.generating) return false

	const { hasToolMessage, isToolSelecting } = detectToolMessage(lastToolMessage.value)
	return hasToolMessage && isToolSelecting
})

// 监听消息变化，当工具调用完成时停止工具加载状态
watch(
	() => props.messages,
	(newMessages, oldMessages) => {
		if (newMessages.length > oldMessages?.length) {
			const latestMessage = newMessages[newMessages.length - 1]
			if (latestMessage?.role === 'assistant') {
				const { isToolCompleted } = detectToolMessage(latestMessage.content)
				// 如果收到工具完成消息，说明当前工具调用结束
				if (isToolCompleted) {
					// 这里可以触发状态更新，通知父组件工具调用完成
					// emit('toolCallCompleted', latestMessage)
				}
			}
		}
	},
	{ deep: true }
)

// 加载更多历史消息
const loadMoreHistory = () => {
	emit('loadMoreHistory')
}

// 处理滚动
const handleScroll = (event: Event) => {
	emit('scroll', event)
}

// 手动滚动到底部
const scrollToBottomManually = () => {
	emit('scrollToBottom')
}

// 暴露messagesContainer引用给父组件
defineExpose({
	messagesContainer,
})
</script>

<style scoped lang="scss">
.messages-container {
	flex: 1;
	padding: 24px;
	overflow-y: auto;
	scroll-behavior: smooth;

	.load-more-container {
		text-align: center;
		padding: 16px 0;
		margin-bottom: 20px;

		.ant-btn {
			border-color: #d9d9d9;
			color: #666;

			&:hover {
				border-color: #40a9ff;
				color: #40a9ff;
			}
		}
	}

	.generating-indicator {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 12px 20px;
		color: #666;
		font-size: 14px;
		background: rgba(59, 130, 246, 0.05);
		border: 1px solid rgba(59, 130, 246, 0.1);
		border-radius: 8px;
		margin: 0 20px 12px 20px;
		justify-content: center;
	}

	.scroll-to-bottom {
		position: absolute;
		bottom: 120px;
		right: 30px;
		z-index: 10;
		animation: fadeInUp 0.3s ease-out;

		.scroll-btn {
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
			border: none;

			&:hover {
				transform: translateY(-2px);
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
			}
		}
	}
}

@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(10px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}
</style>
